package cn.forge.mall.framework.security.core.util;

import cn.forge.mall.framework.security.core.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;

/**
 * @author liangyuanping
 * @ClassName SecurityFrameworkUtils
 * @description: 安全服务工具类
 * @date 2024年03月20日
 * @version: 1.0
 */
public class SecurityFrameworkUtils {


    private static final String AUTHORIZATION_HEADER = "Authorization";
    /**
     * HEADER 认证头 value 的前缀
     */
    public static final String AUTHORIZATION_BEARER = "Bearer";
    public static final String LOGIN_USER_HEADER = "login-user";

    /**
     * header请求头获取token
     *
     * @param request
     * @return
     */
    public static String obtainAuthorization(HttpServletRequest request) {
        String authorization = request.getHeader(AUTHORIZATION_HEADER);
        if (!StringUtils.hasText(authorization)) {
            return null;
        }
        int index = authorization.indexOf(AUTHORIZATION_BEARER + " ");
        if (index == -1) { // 未找到
            return null;
        }
        return authorization.substring(index + 7).trim();
    }


    /**
     * 从Spring Security 上下文中获取当前这个人的认证信息
     * 凭什么得到当前这个人的认证信息 ？？？
     * <p>
     * 1、调用接口会先经过拦截器 TokenAuthenticationFilter 然后得到认证token
     * 2、将认证信息塞进上下文
     *
     * @return
     */
    public static Authentication getAuthentication() {
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        return context.getAuthentication();
    }

    /**
     * 获取当前用户 LoginUser
     *
     * @return
     */
    public static LoginUser getLoginUser() {
        Authentication authentication = getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
    }

    /**
     * 上下文中获取登录用户id
     *
     * @return
     */
    public static Long getLoginUserId() {
        LoginUser loginUser = getLoginUser();
        return loginUser != null ? loginUser.getId() : null;
    }

    /**
     * 将用户信息放入 Spring Security 上下文中，提当前线程后续流程获取
     *
     * @param loginUser
     * @param request
     */
    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request) {
        // 创建 Authentication，并设置到上下文
        Authentication authentication = buildAuthentication(loginUser, request);
        SecurityContextHolder.getContext().setAuthentication(authentication);
    }

    private static Authentication buildAuthentication(LoginUser loginUser, HttpServletRequest request) {
        // 创建 UsernamePasswordAuthenticationToken 对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                loginUser, null, Collections.emptyList());
        authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
        return authenticationToken;
    }
}
